package com.bwie.es.synchronous;

import com.alibaba.fastjson.JSONObject;
import com.bwie.common.domain.Shop;
import com.bwie.es.remote.EsRemote;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.List;

@Component
@Slf4j
public class ShopSynchronous implements ApplicationRunner{

    @Autowired
    private EsRemote esRemote;

    @Autowired
    private RestHighLevelClient restHighLevelClient;

    private static final String INDEX_NAME = "shop";

    @Override
    public void run(ApplicationArguments args){
        try {
            log.info("----------开始同步数据到ES----------");
            long startTime = System.currentTimeMillis();
            log.info("开始时间:{}"+startTime);
            List<Shop> shopList = esRemote.queryShop().getData();
            BulkRequest bulkRequest = new BulkRequest();
            shopList.forEach(shop -> {
                bulkRequest.add(
                        new IndexRequest(INDEX_NAME)
                                .id(String.valueOf(shop.getShopId()))
                                .source(JSONObject.toJSONString(shop), XContentType.JSON)
                );
            });
            restHighLevelClient.bulk(bulkRequest, RequestOptions.DEFAULT);
            log.info("----------结束同步数据到ES----------");
            long endTime = System.currentTimeMillis();
            log.info("开始时间:{}"+endTime);
            log.info("耗时:{}"+(endTime-startTime)/6000);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
